package com.cloudkinto.controller.platform;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dto.platform.product.PlatformProductDto;
import com.cloudkinto.service.platform.PlatformProductService;
import com.cloudkinto.service.platform.vo.product.*;
import com.cloudkinto.service.stock.vo.snap.ProductWeightReq;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hua
 * @since 2025-01-02
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "产品映射模块")
@RequestMapping("/api/admin/oms/PlatformProduct")
public class PlatformProductOmsController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(PlatformProductOmsController.class);

    private final PlatformProductService service;


    @UserSessionRequired
    @PutMapping
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated PlatformUpdateReq req) {
        Long userId = getCurrentUserId();
        service.updateProduct(req, userId, getCompanyId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @PutMapping("/updatePlatformProductAndReturnStock")
    @ApiOperation(value = "fba调拨配对", notes = "fba调拨配对")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = AllocatePlatformUpdateRes.class))
    public SingleResult updatePlatformProductAndReturnStock(@RequestBody @Validated AllocatePlatformUpdateReq bo) {
        return SingleResult.success(service.updatePlatformProductAndReturnStock(bo, getCurrentUserId(), getTenantId(), getCompanyId()));
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit(@PathVariable("id") Long id) {
        return SingleResult.success(service.updateInit(id, getCompanyId()));
    }


    @UserSessionRequired
    @PostMapping
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated PlatformAddReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.add(req, userId, companyId));
    }


    @UserSessionRequired
    @DeleteMapping("/updateDelete")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    public SingleResult delete(@RequestBody @Validated List<Long> ids) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(ids, userId));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCompanyId());
    }

//    @UserSessionRequired
//    @GetMapping("/list")
//    @ApiOperation(value = "查询", notes = "查询")
//    public SingleResult list(HttpServletRequest request){
//        Long companyId = getCompanyId();
//
//        Map<String, Object> map = new HashMap<>();
//        String keyword = request.getParameter("keyword");
//        map.put("keyword", keyword);
//        return SingleResult.success("查询成功", service.getList(map));
//    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dateColumn", value = "筛选日期类型 create_time(创建时间)"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "storeId", value = "店铺id"),
            @ApiImplicitParam(name = "productPresale", value = "预售"),
            @ApiImplicitParam(name = "platformCode", value = "平台类型"),
            @ApiImplicitParam(name = "platformSku", value = "平台sku-模糊搜索"),
            @ApiImplicitParam(name = "fulfillmentChannelCode", value = "配送类型 FBM 传DEFAULT FBA 传AMAZON_JP"),
            @ApiImplicitParam(name = "platformSkuAccurate", value = "平台sku-精准搜索"),
            @ApiImplicitParam(name = "parentSku", value = "父sku-模糊搜索"),
            @ApiImplicitParam(name = "parentSkuAccurate", value = "父sku-精准搜索"),
            @ApiImplicitParam(name = "asin", value = "ASIN"),
            @ApiImplicitParam(name = "fnSku", value = "FNSKU"),
            @ApiImplicitParam(name = "match", value = "产品映射 0 否 1是"),
            @ApiImplicitParam(name = "inventoryLink", value = "库存联动"),
            @ApiImplicitParam(name = "inventoryLess", value = "低库存 0否 1是"),
            @ApiImplicitParam(name = "sku", value = "系统sku-模糊搜索"),
            @ApiImplicitParam(name = "productName", value = "产品名称-模糊搜索"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小"),

    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = PlatformProductDto.class))
    public PageResult listPage(HttpServletRequest request) {

        Map<String, Object> map = this.getMap(request);
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        map.put("current", current);
        map.put("pageSize", size);
        return service.getListPage(map);
    }

    public Map<String, Object> getMap(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", getTenantId());
        map.put("companyId", getCompanyId());
        String inventoryLink = request.getParameter("inventoryLink");
        map.put("inventoryLink", inventoryLink);
        String fulfillmentChannelCode = request.getParameter("fulfillmentChannelCode");
        map.put("fulfillmentChannelCode", fulfillmentChannelCode);
        String inventoryLess = request.getParameter("inventoryLess");
        map.put("inventoryLess", inventoryLess);
        String productPresale = request.getParameter("productPresale");
        map.put("productPresale", productPresale);
        String dateColumn = request.getParameter("dateColumn");
        map.put("dateColumn", dateColumn);
        String beginTime = request.getParameter("beginTime");
        map.put("beginTime", beginTime);
        String endTime = request.getParameter("endTime");
        map.put("endTime", endTime);
        String platformSku = request.getParameter("platformSku");
        if (StringUtils.isNotBlank(platformSku)) {
            map.put("platformSku", platformSku.trim());
        }
        String platformSkuAccurate = request.getParameter("platformSkuAccurate");
        if (StringUtils.isNotBlank(platformSkuAccurate)) {
            map.put("platformSkuAccurate", platformSkuAccurate.trim());
        }
        String match = request.getParameter("match");
        map.put("match", match);

        String parentSku = request.getParameter("parentSku");
        if (StringUtils.isNotBlank(parentSku)) {
            map.put("parentSku", parentSku.trim());
        }
        String parentSkuAccurate = request.getParameter("parentSkuAccurate");
        if (StringUtils.isNotBlank(parentSkuAccurate)) {
            map.put("parentSkuAccurate", parentSkuAccurate.trim());
        }
        String asin = request.getParameter("asin");
        if (StringUtils.isNotBlank(asin)) {
            map.put("asin", asin.trim());
        }
        String fnSku = request.getParameter("fnSku");
        if (StringUtils.isNotBlank(fnSku)) {
            map.put("fnSku", fnSku.trim());
        }
        String sku = request.getParameter("sku");
        if (StringUtils.isNotBlank(sku)) {
            map.put("sku", sku.trim());
        }
        String platformCode = request.getParameter("platformCode");
        if (StringUtils.isNotBlank(platformCode)) {
            map.put("platformCode", platformCode.trim());
        }

        String storeId = request.getParameter("storeId");
        map.put("storeId", storeId);
        String ids = request.getParameter("ids");
        if (StringUtils.isNotBlank(ids)) {
            map.put("ids", Arrays.asList(ids.split(",")));
        }
        String sort = request.getParameter("sort");
        String sortColumn = request.getParameter("sortColumn");
        map.put("sort", sort);
        map.put("sortColumn", sortColumn);

        return map;
    }

    @UserSessionRequired
    @GetMapping("/getPlatformProductTemplate")
    @ApiOperation(value = "获取导入产品映射模板", notes = "获取导入产品映射模板")
    public void getPlatformProductTemplate(HttpServletResponse response) throws Exception {
        service.getPlatformProductTemplate(response, getCompanyId());
    }

    @UserSessionRequired
    @PostMapping("/importT")
    @ApiOperation(value = "导入产品映射")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = PlatformProductImportRes.class))
    public SingleResult importT(MultipartFile file) {
        PlatformProductImportRes platformProductImportRes = service.importT(file, getCurrentUserId(), getCompanyId(), getTenantId());
        return SingleResult.success(platformProductImportRes);
    }


    @UserSessionRequired
    @GetMapping("/platformProductExport")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dateColumn", value = "筛选日期类型 create_time(创建时间)"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "storeId", value = "店铺id"),
            @ApiImplicitParam(name = "platformSku", value = "平台sku"),
            @ApiImplicitParam(name = "sku", value = "系统sku"),
            @ApiImplicitParam(name = "ids", value = "多个逗号隔开"),
            @ApiImplicitParam(name = "productName", value = "产品名称"),

    })
    @ApiOperation(value = "导出")
    public void platformProductExport(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = this.getMap(request);
        service.platformProductExport(map, response);
    }


    @UserSessionRequired
    @PostMapping("manualSyncPlatformProduct")
    @ApiOperation(value = "手动同步商品", notes = "手动同步商品")
    public SingleResult manualSyncPlatformProduct(@RequestBody @Validated ManualSyncPlatformProductReq req) {
        Long userId = getCurrentUserId();
        service.manualSyncPlatformProduct(req, userId);
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/getPlatformProductUpdateTemplate")
    @ApiOperation(value = "获取导入更新库存联动 模板", notes = "获取导入更新库存联动")
    public void getPlatformOrderTrackTemplate(HttpServletResponse response) throws Exception {
        service.getPlatformProductUpdateTemplate(response, getCompanyId());
    }

    @UserSessionRequired
    @PostMapping("/importBatchUpdate")
    @ApiOperation(value = "导入更新库存联动 预售等", notes = "导入更新库存联动 预售等")
    public SingleResult importBatchUpdate(MultipartFile file) {
        service.importBatchUpdate(file, getCurrentUserId(), getCompanyId());
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/getPlatformProductDeleteParentSkuTemplate")
    @ApiOperation(value = "获取导入删除平台产品模板(parentSku)", notes = "获取导入删除平台产品模板(parentSku)")
    public void getPlatformProductDeleteParentSkuTemplate(HttpServletResponse response) throws Exception {
        service.getPlatformProductDeleteParentSkuTemplate(response, getCompanyId());
    }

    @UserSessionRequired
    @GetMapping("/getPlatformProductDeletePlatformSkuTemplate")
    @ApiOperation(value = "获取导入删除平台产品模板(platformSku)", notes = "获取导入删除平台产品模板(platformSku)")
    public void getPlatformProductDeletePlatformSkuTemplate(HttpServletResponse response) throws Exception {
        service.getPlatformProductDeletePlatformSkuTemplate(response, getCompanyId());
    }


    @UserSessionRequired
    @PostMapping("/importDeletePlatformSku")
    @ApiOperation(value = "根据平台sku导入删除", notes = "根据平台sku导入删除")
    public SingleResult importDeletePlatformSku(MultipartFile file) {
        service.importDelete(file, 0, getCurrentUserId(), getCompanyId());
        return SingleResult.success();
    }


    @UserSessionRequired
    @PostMapping("/importDeleteParentSku")
    @ApiOperation(value = "根据管理番号导入删除", notes = "根据管理番号导入删除")
    public SingleResult importDeleteParentSku(MultipartFile file) {
        service.importDelete(file, 1, getCurrentUserId(), getCompanyId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("/updateInventoryBatch")
    @ApiOperation(value = "批量更新库存预留占比", notes = "批量更新库存预留占比")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "updateInventoryLink", value = "修改值 是否库存联动"),
            @ApiImplicitParam(name = "updateStockPercent", value = "修改值 库存预留占比"),
            @ApiImplicitParam(name = "updateProductPresale", value = "修改值 预售"),
            @ApiImplicitParam(name = "updateShippingDayId", value = "修改值 配货准备日期"),
            @ApiImplicitParam(name = "updateType", value = "0 按id 1按管理番号(当管理番号 空时 不可选) 2 按当前筛选条件"),
            @ApiImplicitParam(name = "ids", value = "数据id 当updateType = 0 时传"),
            @ApiImplicitParam(name = "parentSkuAccurates", value = "管理番号，当updateType = 1 时传"),

    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = PlatformProductDto.class))
    public SingleResult updateInventoryBatch(HttpServletRequest request) {

        Map<String, Object> map = this.getMap(request);
        String updateInventoryLink = request.getParameter("updateInventoryLink");
        String updateStockPercent = request.getParameter("updateStockPercent");
        String updateProductPresale = request.getParameter("updateProductPresale");
        String updateShippingDayId = request.getParameter("updateShippingDayId");

        String updateType = request.getParameter("updateType");
        String ids = request.getParameter("ids");
        String parentSkuAccurates = request.getParameter("parentSkuAccurates");
        map.put("updateInventoryLink", updateInventoryLink);
        map.put("updateStockPercent", updateStockPercent);
        map.put("updateProductPresale", updateProductPresale);
        map.put("updateShippingDayId", updateShippingDayId);
        map.put("updateType", updateType);
        if (updateType != null && updateType.equals("0")) {
            map.put("ids", Arrays.asList(ids.split(",")));
        } else if (updateType != null && updateType.equals("1")) {
            map.put("parentSkuAccurates", Arrays.asList(parentSkuAccurates.split(",")));
        }
        map.put("companyId", getCompanyId());
        map.put("userId", getCurrentUserId());
        service.updateInventoryBatch(map);
        return SingleResult.success();
    }


    @UserSessionRequired
    @PostMapping("/addWeight")
    @ApiOperation(value = "产品映射设置权重", notes = "产品映射设置权重")
    public SingleResult addWeight(@RequestBody @Validated ProductWeightReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("修改成功", service.addWeight(req, userId, companyId));
    }


}

